import re
from functools import lru_cache

from app.config import decrypt_dbs_path, wechat_root
from app.db.db import Db
from app.utils import get_str_md5


@lru_cache(None)
def get_my_user():
    user_md5 = wechat_root.rstrip("/").split("/")[-1]
    db = Db(decrypt_dbs_path, "group_new.db")
    for line in db.exec_sql("select * from GroupMember"):
        if user_md5 == get_str_md5(line[0]):
            return line


@lru_cache(None)
def get_group_name(m_nsUsrName):
    db = Db(decrypt_dbs_path, "group_new.db")
    data = db.exec_sql("select nickname from GroupContact where m_nsUsrName='{}'".format(m_nsUsrName))
    return data[0]


@lru_cache(None)
def get_chat_session_list():
    # 获取群聊列表
    db = Db(decrypt_dbs_path, "session_new.db")
    result = []
    n = 0
    for line in db.exec_sql("select * from SessionAbstract order by m_uLastTime desc"):
        # print(line[0])
        name_md5 = get_str_md5(line[0])
        if not is_exist(name_md5):
            continue

        if '@chatroom' in line[0]:
            nickname = get_group_name(line[0])[0]
        else:
            user_info = get_user_info_by_wxid(line[0])
            nickname = user_info[5] or user_info[2]

        result.append({
            "m_nsUsrName": line[0],
            "nickname": nickname,
            "m_nsUsrName_md5": name_md5,
            "i": n,
        })
        n += 1

    return result


@lru_cache(None)
def is_exist(name_md5):
    for i in range(10):
        db = Db(decrypt_dbs_path, "msg_{}.db".format(i))
        data = db.exec_sql("SELECT name FROM sqlite_master WHERE type='table' and name like '%{}%'".format(name_md5))
        if data:
            if "dels" not in data[0][0]:
                return True

    return False


def get_msg_db(name_md5):
    for i in range(10):
        db_file_path = "msg_{}.db".format(i)
        db = Db(decrypt_dbs_path, db_file_path)
        data = db.exec_sql("SELECT name FROM sqlite_master WHERE type='table' and name like '%{}%'".format(name_md5))
        if data:
            return db, data[0][0], db_file_path
    return None, None


def get_msg(m_nsUsrName, page, order_by):
    # 获取聊天记录
    # print("m_nsUsrName", m_nsUsrName)
    page_size = 10
    name_md5 = get_str_md5(m_nsUsrName)
    db, table_name, db_file_path = get_msg_db(name_md5)
    print(db, table_name, db_file_path)
    if not table_name or "dels" in table_name:
        return []
    result = []
    for i in db.exec_sql("select * from {} order by mesLocalID {} limit {},{} ".format(
            table_name, order_by, (page - 1) * page_size, page * page_size)):
        sender_wxid = ""
        if i[6] == 10000:
            # 系统消息
            sender_wxid = i[3].split(":\n")[0]
        elif i[7] == 0 and i[6] != 10000:
            sender_wxid = "我"
            user = get_my_user()
            if user:
                sender_wxid = user[0]
        elif i[8]:
            if "@chatroom" not in m_nsUsrName:
                sender_wxid = m_nsUsrName

            else:
                # _sender_wxids = re.findall(r"^([@,\w]+?):", i[3])
                _sender_wxids = i[3].split(":\n")
                if _sender_wxids:
                    sender_wxid = _sender_wxids[0]
                    print("sender_wxid", i[6], i[7], sender_wxid)

        msgContent = i[3]
        if i[7] == 1:
            msgContent = msgContent.lstrip(sender_wxid)
            msgContent = msgContent.lstrip(":")

        result.append({
            'mesLocalID': i[0],
            "name_md5": name_md5,
            "mesSvrID": i[1],
            "msgCreateTime": i[2],
            "msgContent": msgContent,
            "msgStatus": i[4],
            "msgImgStatus": i[5],
            "messageType": i[6],
            "msgDes": i[7],
            "msgSource": i[8],
            "sender_wxid": sender_wxid,
            "is_me": bool(i[7] == 0),
        })

    return result


@lru_cache(None)
def get_user_info_by_wxid(wxid):
    if not wxid:
        return
    db = Db(decrypt_dbs_path, "wccontact_new2.db")
    users = db.exec_sql("select * from WCContact where m_nsUsrName='{}'".format(wxid))
    if users:
        return users[0]

    db = Db(decrypt_dbs_path, "group_new.db")
    users = db.exec_sql("select * from GroupMember where m_nsUsrName='{}'".format(wxid))
    if users:
        return users[0]

# def get_wccontact_info(m_nsUsrName):
#     db = Db(decrypt_dbs_path, "wccontact_new2.db")
#     data = db.exec_sql("select * from WCContact where m_nsUsrName='{}'".format(m_nsUsrName))
#     return data[0]
